package engine.newUi
{
	import engine.control.TurnPapersViewGroup;
	import engine.data.BindManage;
	import engine.data.ModelLocator;
	import engine.data.ResPath;
	import engine.data.View;
	import engine.data.ViewObject;
	import engine.flag.ResourcesPath;
	import engine.logic.DoubleClickManager;
	import engine.logic.event.LogicEvent;
	import engine.net.event.CustomMsgEvent;
	import engine.net.messages.CustomToClientFlag;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	import engine.scene.SceneManager;
	import engine.tip.TipsMainLogic;
	import engine.ui.AlertUI;
	import engine.ui.UIManage;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import newx.BaseObject;
	import newx.StageInfo;
	import newx.com.config.StaticIni;
	import newx.com.control.NxClip;
	import newx.com.control.group.NxViewGroup;
	import newx.com.control.text.NxLabel;
	import newx.com.control.window.NxWindowEvent;
	import newx.utils.MemoryOptimise;
	import newx.utils.MouseHandle;
	
	/**
	 * 宝物商店逻辑 
	 * @author liuel
	 * 
	 */	
	public class TreasureShopLogic
	{
		/**
		 * 0,
		 * 1,白
		 * 2.绿
		 * 3.蓝
		 * 4.紫红
		 * 5.橙黄
		 * 6.黄
		 * 7.浅黄
		 */		
		protected const COLOR_TABLE	:Array	=	["","#ffffff'>","#1eff00'>","#20BFF8'>","#a335ee'>","#E8912E'>","#e5cc80'>","#ffff00'>"];
		private static var _self			:TreasureShopLogic;
		public var ui						:TreasureShopUI;
		private var _packui				:PackUI;
		/**数据模型*/
		private var _model					:ModelLocator;
		private var _bind					:BindManage;
		private var bindFlag:int			=	-1;
		private var bindDeport:int			=	-1;
		private var bindView:int			=	-1;
		private var _typeTab				:int    =               1;
		private var _itemMC				:MovieClip
		private var _img					:NxClip;
		private var _txtCount				:NxLabel;
		
		private var  _txt1					:NxLabel;
		private var  _txt2					:NxLabel;
		private var _isSend				:Boolean =               false;
		/**第一次点击时间**/
		private var _fristTime				:int;
		/**翻页**/		
		private var _tableListener			:TurnPapersViewGroup;
		private var _time					:Timer;
		private var  _mc					:MovieClip;
		private var _overMc				:MovieClip;
		private var _clickMc				:MovieClip;
		private var _mouse					:MouseHandle;
		
		private var _doubleClick			:DoubleClickManager;
		//拖动的图片
		private var _dragmc:NxClip;
		
		private var  dragItem:Object;
		/**
		 * Group状态
		 * BASIV_STATE	普通状态
		 * ROLL_STATE   滑动状态
		 * CLICK_STATE  点击状态
		 * DISUSE_STATE 不能用状态
		 */		
		private const BASIV_STATE			:int	= 1;
		private const 	ROLL_STATE          :int	= 2;
		private const 	CLICK_STATE         :int	= 3;
		private const 	DISUSE_STATE		:int	= 4;
		
		//玉牌数组
		private var _yupaiItems:Array;
		//材料令
		private var _cailiaoItems:Array;
		
		//材料ID数组
		private var _itemsCountArr:Array = new Array({configid:33020001,Amount:0}, {configid:33020002,Amount:0},
														{configid:33020003,Amount:0}, {configid:33020004,Amount:0}, 
														{configid:33020005,Amount:0}, {configid:33020006,Amount:0});
		
		public static function getInstance():TreasureShopLogic
		{
			if(_self == null)
			{
				_self = new TreasureShopLogic();
				
			}
			return _self;
		}
		
		public function TreasureShopLogic()
		{
		}
		
		public function Init():void
		{
			ui              = TreasureShopUI.getInstance();
			_packui         = PackLogic.getInstance().ui;
			_bind			= BindManage.getInstance();
			initInfo();
			_tableListener	= new  TurnPapersViewGroup(ui.imgGroup,ui.btnPre,ui.btnNext,showItem,removeItem,afterShowItem,ui.pagelabel);
			_model          = ModelLocator.getInstance(); 
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_OPEN_TREASURE_SHOP_UI),onOpenTrade);
			_mouse			= MouseHandle.getInstance();
			_doubleClick	= DoubleClickManager.getInstance();
			_doubleClick.addDoubleClick(TreasureShopLogic,clikFunction,doubleClickFunction);
		}
		
		public function BeforeShow():void
		{
//			if(!SceneManager._itemIconLoad)
//			{
//				_model.addEventListener(LogicEvent.ITEMICONLOADED,loaded);
//				function loaded():void
//				{
//					BeforeShow();
//					_model.removeEventListener(LogicEvent.ITEMICONLOADED,loaded)
//				}
//			}
			ui.mc1.source	= ResPath.PNG + "jianghuling.png";
			_typeTab=1;
			ui.typeTab.selected=0;
			addEvent();
			_yupaiItems		= new Array();
			_cailiaoItems	= new Array();
			//绑定道具数量
			bind();
			//获取道具数量
			getCount();
		}
		
		private function getCount():void
		{
			for(var i:int = 0; i < _itemsCountArr.length; i++){
				var count:int = ComposeItemLogic.getInstance().searchItem(_itemsCountArr[i].configid, 1);
				_itemsCountArr[i].Amount = count;
			}
			showText();
		}
		
		private function showText():void
		{
			if(_typeTab == 1){
				ui.riverlakeLabel.htmlText	= StaticIni.getSwfLangStrVar("UIString_1000648", [_itemsCountArr[0].Amount, _itemsCountArr[1].Amount,
					_itemsCountArr[2].Amount, _itemsCountArr[3].Amount, _itemsCountArr[4].Amount]);
			} else {
				ui.riverlakeLabel.htmlText	= StaticIni.getSwfLangStrVar("UIString_1000649", [_itemsCountArr[5].Amount]);
			}
		}
		
		private function bind():void
		{
			if( bindFlag == -1 )
			{
				bindFlag	= _bind.BindView(_model.scene,View.VIEWPORT_TOOL, OnAddPack, OnRemovePack, null, updateitemsAmount);
			}
			if( bindDeport == -1){
				bindDeport	= _bind.BindView(_model.scene,View.VIEWPORT_STORE,OnAddPack, OnRemovePack, null, updateitemsAmount);
			}
		}
		
		private function unBind():void
		{
			if( bindFlag != -1 )
			{
				bindFlag	= _bind.UnbindView(View.VIEWPORT_TOOL,bindFlag);
			}
			if( bindDeport != -1){
				bindDeport	= _bind.UnbindView(View.VIEWPORT_DEPOT, bindDeport);
			}
			
		}
		
		public function AfterHide():void
		{
			unBind();
			removeEvent();
		}
		
		private function addEvent():void
		{
			ui.windowBG.addEventListener(NxWindowEvent.WINDOW_CLOSE,onClickClose);
			ui.typeTab.addEventListener(MouseEvent.CLICK,onSetList);
			ui.imgGroup.addItemsEvent(MouseEvent.MOUSE_OUT,onItemOut);
			ui.imgGroup.addItemsEvent(MouseEvent.MOUSE_OVER,onItemOver);
			ui.imgGroup.addItemsEvent(MouseEvent.CLICK,onClickGroup);
			ui.mc1.addEventListener(MouseEvent.MOUSE_OVER, mcTipsOver);
			ui.mc1.addEventListener(MouseEvent.MOUSE_OUT, mcTipsOut);
			_tableListener.addListener();
		}
		
		public function BindFunc(PropertiesName:String,PropertiesValue:*,pList:Array):void
		{
			var	Obj:NxLabel		=	pList[0];
			var	value:*			=	pList[1];
			var perWidth:int	=	5;
			Obj[value]=PropertiesValue;	
		}
		
		private function removeEvent():void
		{
			ui.windowBG.removeEventListener(NxWindowEvent.WINDOW_CLOSE,onClickClose);
			ui.typeTab.removeEventListener(MouseEvent.CLICK,onSetList);
			ui.imgGroup.removeItemsEvent(MouseEvent.ROLL_OUT,onItemOut);
			ui.imgGroup.removeItemsEvent(MouseEvent.ROLL_OVER,onItemOver);
			ui.imgGroup.removeItemsEvent(MouseEvent.CLICK,onClickGroup);
			ui.mc1.removeEventListener(MouseEvent.MOUSE_OVER, mcTipsOver);
			ui.mc1.removeEventListener(MouseEvent.MOUSE_OUT, mcTipsOut);
			_tableListener.removeListener();
		}
		
		private function initInfo():void
		{
			ui.typeTab.seletedLabelColor= 0xc5ffdc;
			ui.typeTab.defaultLabelColor= 0x648a7a;
			ui.typeTab.clearItems();
			ui.typeTab.addItem(StaticIni.getSwfLangStr("ImportStr_3"));
			ui.typeTab.addItem(StaticIni.getSwfLangStr("ItemType_100"));
			initGroup(ui.imgGroup);
			
		}
		private function initGroup(group:NxViewGroup):void
		{
			for (var i : int = 0; i <  group.row*group.col; i++)
			{
				_txt1	= 	new NxLabel();
				_txt2	=	new NxLabel();
				_itemMC	=	group.getItemByIndex(i);
				MemoryOptimise.stopMovie(_itemMC);
				_img		=	new NxClip(); 
				_img.x = _itemMC["img2"].x;
				_img.y = _itemMC["img2"].y;
				_img.defaultImage   =	null;
				_img.isCache		=	true;
				_img.source         =   null;
				
				_itemMC["img"]     =   _img;
				_itemMC["titleTxt1"] = _txt1;
				_itemMC["titleTxt1"].x =_itemMC["titleTxt"].x;
				_itemMC["titleTxt1"].y =_itemMC["titleTxt"].y;
				_itemMC["infoTxt1"]  = _txt2;
				_itemMC["infoTxt1"].x =_itemMC["infoTxt"].x;
				_itemMC["infoTxt1"].y =_itemMC["infoTxt"].y;
				_itemMC["infoTxt"].text = _itemMC["titleTxt"].text ="";
				_itemMC.addChild(_txt1);
				_itemMC.addChild(_txt2);
				_itemMC.addChild(_img);
			}
		}
		
////////////////////////////////////////////翻页回调////////////////////////////////////////////////////////
		
		/**
		 * 显示对象
		 * @param	mc
		 * @param	data
		 */
		public function showItem(mc:MovieClip,data:Object):void 
		{
			var itemObject:Object			= StaticIni.getIniObj(data["ConfigID"]);
			(mc["img"]	as NxClip).source	= data["Photo"];
			mc["titleTxt1"].htmlText		= link_color(data["NameID"],int(itemObject["Color"]));
			if(int(data["type"]) == 2)
			{
				mc["infoTxt1"].htmlText 	= link_color(setShowGoldStr(int(data["type"]),int(data["kind"]))+"x",0)
					+link_color(data["gold"],0)+"";
			}
			mc["data"]				=	data;
			mc.addEventListener(MouseEvent.MOUSE_DOWN,StarDrag);
		}
		/**
		 * 删除对象
		 * @param	mc
		 */
		public function removeItem(mc:MovieClip):void 
		{
			(mc["img"]	as NxClip)	.clear();
			(mc["img"]	as NxClip)	.source	=	null;
			mc["titleTxt1"]		    .text 	=	"";
			mc["infoTxt1"] 		    .text 	=	"";
			mc["data"]						=	null;
			mc.removeEventListener(MouseEvent.MOUSE_DOWN,StarDrag);
		}
		/**
		 * 翻页后的操作
		 */
		public function afterShowItem():void
		{
			if( _clickMc != null )
			{
				_clickMc["dt_mc"].gotoAndStop(BASIV_STATE);
			}
		}
		
		private function onClickGroup(e:MouseEvent):void
		{
			_doubleClick.onClick(TreasureShopLogic,e);
		}
		
		private function clikFunction(e:MouseEvent):void
		{
			
		}
		
		private function doubleClickFunction(e:MouseEvent):void
		{
			_itemMC = e.currentTarget as MovieClip;
			var dateils:Object	=	e.currentTarget.data;
			if(dateils ==null)
				return;
			//点击的是买卖栏
			if(e.currentTarget.parent == ui.imgGroup)
			{
				var itemName:String = StaticIni.getSwfLangStr(dateils["NameID"]);
				//双击击购买一个
				SystemSender.getInstance().CustomMsg(
					CustomToServerFlag.CLIENT_CUSTOMMSG_TRADE_WITHNPC,0,View.VIEWPORT_TOOL,dateils["ConfigID"],-1,1);
			}
		}
		
		private function StarDrag(e:MouseEvent):void
		{
			var mc:MovieClip=e.currentTarget as MovieClip;
			if(mc && mc["img"].content)
			{
				_mouse.setItem(mc,mc["img"].content,true,mc["data"]);
				_packui.group.addItemsEvent(MouseEvent.MOUSE_UP,  fun);
				_packui.group.addItemsEvent(MouseEvent.MOUSE_DOWN,  downfun);
				UIManage.getInstance().maskEnable=false
			}  
		}
		
		private function downfun(e:MouseEvent):void
		{
			_mouse.removeDrag();
		}
		
		private function fun(e:MouseEvent):void
		{
			var mc:MovieClip = e.currentTarget as MovieClip;
			var i:int = _packui.group.getChildIndex(mc);
			_packui.group.removeItemsEvent(MouseEvent.MOUSE_UP,  fun);
			var dateils:Object	=	_mouse.targetData;
			if(dateils == null) return;
			var configIDT:int=0;
			configIDT=dateils["ConfigID"];
			
			//拖动的物品
			var dragItem:Object=StaticIni.getIniObj(String(configIDT));
			if(dragItem == null)
				return;
			var itemName:String = StaticIni.getSwfLangStr(dragItem["NameID"]);
			//拖动购买多个
			AlertUI.showAlert(StaticIni.getSwfLangStr("SellUI_Buy"),StaticIni.getSwfLangStrVar("UIString_1000004",[" "+itemName+" "]),AlertUI.YES|AlertUI.NO,sendBuy,[_mouse.targetData],true,300,150,"1","0-9");
			_mouse.removeDrag();
		}
		
		private function StopDrag(e:MouseEvent):void
		{
			_packui.group.removeItemsEvent(MouseEvent.MOUSE_UP,  fun);
			StageInfo.stage.removeEventListener(MouseEvent.MOUSE_UP,  StopDrag);
		}
		
		protected function link_color(str:String,color:int):String
		{
			if(color < 1 || color >8)
			{
				color	=	1;
			}
			return ("<font color ='"+COLOR_TABLE[color]+str+"</font>");
		}
		
		/**
		 * 确定购买 
		 * @param targetName
		 * @param inputTxt
		 * @param data
		 * 
		 */		
		private function sendBuy(targetName:int,inputTxt:String,data:Array):void
		{
			if(targetName	==	AlertUI.YES)
			{
				var objData:Object	=	data[0];
				var amount:uint		=	1;
				if(inputTxt!=""&&inputTxt!=null)
				{
					amount	=	int(inputTxt);
				}
				
				SystemSender.getInstance().CustomMsg(
					CustomToServerFlag.CLIENT_CUSTOMMSG_TRADE_WITHNPC,0,View.VIEWPORT_TOOL,objData["ConfigID"],-1,amount);
			}
		}
		
		/**
		 * 打开商店和仓库 
		 * 
		 */		
		private function openSellMoive():void
		{
			if(ui.created == false)
			{
				ui.showOrHide();
			}
			if(_packui.created == false)
			{
				_packui.showOrHide();
			}
		}
		
		/**
		 * 播放打开仓库和商店效果
		 * @param e
		 * 
		 */		
		private function onPlay(e:TimerEvent):void
		{
			var speed:Number = _packui.windowBG.width/2/_time.repeatCount;
			ui.windowBG.x-=speed;
			_packui.windowBG.x+=speed;
			if(_time.currentCount == _time.repeatCount)
			{
				_time.reset();
			}
			
		}
////////////////////////////////////////////////////////侦听函数//////////////////////////////////////////////////////////////////
		
		/**
		 * 打开商店 接受数据
		 * @param e
		 * 
		 */		
		private function onOpenTrade(e:CustomMsgEvent):void
		{
			var pList : Array = e.pList;
			openSellMoive();
			_tableListener.clear();
			
			var obj:Object;
			var itemObj:Object;
			for (var i:int=0;i<pList.length;i+=4)
			{
				obj 	= new Object();
				
				itemObj = StaticIni.getIniObj(pList[i]);
				obj["ConfigID"]  	= pList[i];
				obj["type"]			= pList[i+1]; //类型  
				obj["kind"]			= pList[i+2]; //种类  1玉牌 6 材料令
				obj["Photo"]       = ResourcesPath.getPropsURL(itemObj["Photo"]);
				obj["gold"]        = pList[i+3];
				obj["NameID"]      = StaticIni.getSwfLangStr(itemObj["NameID"]);
				
				if(obj["kind"]	< 6 && obj["kind"] > 0){
					_yupaiItems.push(obj);
				} else if(obj["kind"]	== 6) {
					_cailiaoItems.push(obj);
				}
			}
			
			checkShow();
		}
		
		private function checkShow():void
		{
			_tableListener.clear();
			if(_typeTab == 1){
				_tableListener.dataProvider	= _yupaiItems;
				ui.mc1.source = ResPath.PNG + "jianghuling.png";
			} else {
				_tableListener.dataProvider	= _cailiaoItems;
				ui.mc1.source = ResPath.PNG + "zhenbaoling.png";
			}
			showText()
		}
		
		private function setShowGoldStr(type:int,kind:int):String
		{
			var strID:String;
			if(type == 2)
			{
				switch(kind)
				{
					case 0:
						strID ="未定义类型"
					case 1:   //白
						strID ="UIString_1000245"
						break;
					case 2:   //绿
						strID ="UIString_1000246"
						break;
					case 3: //蓝
						strID ="UIString_1000247"
						break;
					case 4:   //紫
						strID ="UIString_1000248"
						break;
					case 5:  //黄
						strID ="UIString_1000249"
						break;
					case 6: //材料令
						strID = "33020006";
						break;
				}
			}
			return StaticIni.getSwfLangStr(strID);
		}
		
		private function onClickClose(e:NxWindowEvent):void
		{
			ui.hide();
		}
		
		/**
		 * 点击Tab 
		 * @param e
		 * 
		 */		
		private function onSetList(e:MouseEvent):void
		{
			_typeTab= ui.typeTab.selected + 1;
			checkShow();
		}
		
		/**
		 * 显示Tips 
		 * @param e
		 * 
		 */		
		private function onItemOver(e:MouseEvent):void
		{
			if( _overMc != null )
			{
				if(_overMc["dt_mc"].currentFrame != CLICK_STATE)
				{
					_overMc["dt_mc"].gotoAndStop(BASIV_STATE);
				}
			}
			_overMc	=	e.currentTarget as MovieClip;
			if(_overMc["dt_mc"].currentFrame != CLICK_STATE)
			{
				_overMc["dt_mc"].gotoAndStop(ROLL_STATE);
			}
			var obj:Object= _overMc.data ;
			if(obj == null)
				return;
			var obb:Object=TipsMainLogic.instance.getStaticObjWithID(obj["ConfigID"]);
			obb["SellValue"]=obj["gold"];
			obb["_type"]= obj["type"];
			obb["_kind"]= obj["kind"];
			TipsMainLogic.instance.showMain(obb,true);
		}
		
		/**
		 * 关闭Tips
		 * @param e
		 * 
		 */		
		private function onItemOut(e:MouseEvent):void
		{
			_overMc = e.currentTarget as MovieClip;
			if(_overMc["dt_mc"].currentFrame != CLICK_STATE)
			{
				_overMc["dt_mc"].gotoAndStop(BASIV_STATE);
			}
			TipsMainLogic.instance.hide();
		}
		
		private function mcTipsOver(e:MouseEvent):void
		{
			if(_typeTab == 1){
				TipsMainLogic.instance.showString(StaticIni.getSwfLangStr("UIString_1000650"));
			} else {
				TipsMainLogic.instance.showString(StaticIni.getSwfLangStr("UIString_1000651"));
			}
		}
		
		private function mcTipsOut(e:MouseEvent):void
		{
			TipsMainLogic.instance.hide();
		}
		
		private function OnAddPack(PropertiesName:String,PropertiesValue:ViewObject,data:*):void
		{
			updateitemsAmount(PropertiesName, PropertiesValue, data);
		}
		
		private function updateitemsAmount(PropertiesName:String,PropertiesValue:ViewObject,data:*):void
		{
			for(var i:String in _itemsCountArr)
			{
				if(_itemsCountArr[int(i)].configid == PropertiesValue.GetProperties("ConfigID"))
				{
					var amount:int = ComposeItemLogic.getInstance().searchItem(_itemsCountArr[int(i)].configid,1);
					_itemsCountArr[int(i)].Amount = amount;
				}
			}
			showText();
		}
		
		private function OnRemovePack(PropertiesName:String,PropertiesValue:ViewObject,data:*):void
		{
			updateitemsAmount(PropertiesName, PropertiesValue, data);
		}
	}
}